package thread.syn;

//不安全买票
public class BuyTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(ticket,"x").start();
        new Thread(ticket,"y").start();
        new Thread(ticket,"z").start();
    }
}

class Ticket implements Runnable{

    private int ticketNums = 10;
    boolean flag = true; //是否有余票

    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }
    }

    //同步，锁的是对象本身->this
    //锁的对象是变化的量，即需要增删改的量
    public synchronized void buy(){
        //判断是否有票
        if(this.ticketNums <=0){
            flag = false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums-- + "张票。");
    }
}